<?php
// 图片文件上传处理接口
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// 日志记录函数
function logMessage($message) {
    $logFile = __DIR__ . '/upload-image.log';
    $timestamp = date('Y-m-d H:i:s');
    $formattedMessage = "[{$timestamp}] {$message}\n";
    @file_put_contents($logFile, $formattedMessage, FILE_APPEND | LOCK_EX);
}

try {
    logMessage("Upload request started");
    
    // 检查是否是POST请求
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        logMessage("Invalid request method: " . $_SERVER['REQUEST_METHOD']);
        throw new Exception('只允许POST请求');
    }
    
    // 检查是否有文件上传数据
    if (!isset($_FILES['file']) || !isset($_FILES['file']['error'])) {
        logMessage("No file data in request");
        throw new Exception('没有文件被上传');
    }
    
    // 检查文件上传是否有错误
    switch ($_FILES['file']['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            logMessage("File size exceeds limit");
            throw new Exception('文件大小超过限制');
        case UPLOAD_ERR_PARTIAL:
            logMessage("File upload incomplete");
            throw new Exception('文件上传不完整');
        case UPLOAD_ERR_NO_FILE:
            logMessage("No file uploaded");
            throw new Exception('没有文件被上传');
        case UPLOAD_ERR_NO_TMP_DIR:
            logMessage("Missing temporary folder");
            throw new Exception('临时文件夹缺失');
        case UPLOAD_ERR_CANT_WRITE:
            logMessage("Failed to write file to disk");
            throw new Exception('文件写入失败');
        case UPLOAD_ERR_EXTENSION:
            logMessage("File upload stopped by extension");
            throw new Exception('文件上传被扩展限制');
        default:
            logMessage("Unknown upload error: " . $_FILES['file']['error']);
            throw new Exception('未知的文件上传错误');
    }
    
    // 获取文件信息
    $file = $_FILES['file'];
    logMessage("File info - name: {$file['name']}, size: {$file['size']}, tmp_name: {$file['tmp_name']}");
    
    // 验证文件基本信息
    if (!is_uploaded_file($file['tmp_name'])) {
        logMessage("Invalid uploaded file");
        throw new Exception('非法文件上传');
    }
    
    // 检查文件大小 (限制为3MB，符合项目规范)
    if ($file['size'] > 3 * 1024 * 1024) {
        logMessage("File size too large: {$file['size']}");
        throw new Exception('文件大小不能超过3MB');
    }
    
    if ($file['size'] == 0) {
        logMessage("File is empty");
        throw new Exception('文件不能为空');
    }
    
    // 获取文件扩展名
    $fileExt = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    logMessage("File extension: {$fileExt}");
    
    // 检查允许的图片文件类型
    $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    if (!in_array($fileExt, $allowedExts)) {
        logMessage("Invalid file extension: {$fileExt}, allowed: " . implode(',', $allowedExts));
        throw new Exception('不支持的图片格式，仅支持: ' . implode(', ', $allowedExts));
    }
    
    // 生成唯一文件名
    $timestamp = time();
    $randomString = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyz'), 0, 8);
    $fileName = $timestamp . '_' . $randomString . '.' . $fileExt;
    logMessage("Generated filename: {$fileName}");
    
    // 定义上传目录
    $basePath = '..';
    $uploadDir = rtrim($basePath . '/uploads/images', '/') . '/';
    logMessage("=== UPLOAD PATH INFORMATION ===");
    logMessage("Base path (relative to PHP file): {$basePath}");
    logMessage("Upload directory: {$uploadDir}");
    logMessage("Full upload directory path: " . realpath($uploadDir));
    logMessage("=== END UPLOAD PATH INFORMATION ===");
    
    // 检查基础路径是否存在
    if (!is_dir($basePath)) {
        logMessage("Base path does not exist: {$basePath}");
        throw new Exception('基础路径不存在');
    }
    
    // 检查上传目录是否存在，不存在则创建
    logMessage("Checking if upload directory exists: " . (is_dir($uploadDir) ? 'yes' : 'no'));
    if (!is_dir($uploadDir)) {
        logMessage("Upload directory does not exist, trying to create it");
        // 尝试创建目录，使用递归模式
        if (!@mkdir($uploadDir, 0755, true)) {
            logMessage("Failed to create upload directory with 0755, trying 0777");
            // 如果失败，尝试使用更宽松的权限
            if (!@mkdir($uploadDir, 0777, true)) {
                logMessage("Failed to create upload directory with 0777");
                throw new Exception('无法创建上传目录');
            }
            logMessage("Upload directory created with 0777");
        } else {
            logMessage("Upload directory created with 0755");
        }
    }
    
    // 检查上传目录是否可写
    logMessage("Checking if upload directory is writable: " . (is_writable($uploadDir) ? 'yes' : 'no'));
    if (!is_writable($uploadDir)) {
        logMessage("Upload directory is not writable, trying to change permissions");
        // 尝试修改权限
        if (!@chmod($uploadDir, 0755)) {
            logMessage("Failed to change permissions to 0755, trying 0777");
            // 如果失败，尝试使用更宽松的权限
            if (!@chmod($uploadDir, 0777)) {
                logMessage("Failed to change permissions to 0777");
                throw new Exception('上传目录不可写');
            }
            logMessage("Permissions changed to 0777");
        } else {
            logMessage("Permissions changed to 0755");
        }
        
        // 再次检查是否可写
        if (!is_writable($uploadDir)) {
            logMessage("Upload directory is still not writable after chmod attempt");
            throw new Exception('上传目录不可写');
        }
        logMessage("Upload directory is now writable");
    }
    
    // 构造完整文件路径
    $filePath = $uploadDir . $fileName;
    logMessage("Target file path: {$filePath}");
    
    // 移动上传的文件
    logMessage("Moving uploaded file from {$file['tmp_name']} to {$filePath}");
    if (!move_uploaded_file($file['tmp_name'], $filePath)) {
        logMessage("Failed to move uploaded file");
        throw new Exception('文件保存失败');
    }
    
    // 检查文件是否成功保存
    if (!file_exists($filePath)) {
        logMessage("File does not exist after move");
        throw new Exception('文件保存失败');
    }
    
    // 设置文件权限
    @chmod($filePath, 0644);
    logMessage("File permissions set to 0644");
    
    // 构造可访问的URL
    $fileUrl = '/uploads/images/' . $fileName;
    logMessage("File uploaded successfully, URL: {$fileUrl}");
    
    // 返回成功响应
    echo json_encode([
        'success' => true,
        'url' => $fileUrl,
        'filename' => $fileName,
        'size' => $file['size']
    ]);
    
} catch (Exception $e) {
    logMessage("Upload error: " . $e->getMessage());
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}